package com.education.welco.controller;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;


@RestController
@RequestMapping("/template")
@CrossOrigin
public class TemplateController {

    /**
     * 七牛桶目录
     */
    private static final String QINIU_FILE_DIRECTORY = "informatization4.0/";
    public static final Logger LOGGER = LogManager.getLogger(TemplateController.class);

    /**
     * 将文本内容写入Excel，然后下载该Excel
     *
     * @param pathfile 待读取的文本路径
     * @param response 响应
     * @param fileName 生成的Excel文件名称  （XXX.xls）
     */
    public void downLoadFile(HttpServletResponse response) {
        String fileName = "studentTemplate.xls";
        String pathfile = getClass().getResource("/template/" + fileName).getPath();
        try {
            //解决下载后的文件中文名乱码问题
            fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("", e);
//			view.viewString(ParamUtils.errorParam("不支持iso-8859-1编码格式"), response);
        }
        //声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        //生成一个表格
        HSSFSheet sheet = workbook.createSheet(fileName);
        //向excel中写入内容
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            fis = new FileInputStream(pathfile);
            isr = new InputStreamReader(fis, "utf-8");
            br = new BufferedReader(isr);

            String line;
            int i = 0;
            //按行读取文件中的内容，然后写入Excel中（PIO也可以设置Excel的样式）
            while ((line = br.readLine()) != null) {
                String str = line;
                String[] splits = str.split(",");
                HSSFRow nrow = sheet.createRow(i);
                for (int j = 0; j < splits.length; j++) {
                    HSSFCell nCell = nrow.createCell(j);
                    nCell.setCellValue(splits[j]);
                }
                i++;
            }
        } catch (FileNotFoundException e) {
            LOGGER.error("指定的读取文件不存在\"", e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("文本内容不能转成 utf-8", e);
        } catch (IOException e) {
            LOGGER.error("写入内容出错", e);
        } finally {
            try {
                fis.close();
                isr.close();
                br.close();
            } catch (IOException e) {
                LOGGER.error("读取流关闭异常", e);
            }
        }

        //输出excel
        response.reset();
        response.setCharacterEncoding("utf-8");
        // Content-disposition 告诉浏览器以下载的形式打开
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        // application/ms-excel;charset=utf-8 告诉浏览器下载的文件是excel
        response.setContentType("application/ms-excel");
        OutputStream out = null;
        try {
            out = new BufferedOutputStream(response.getOutputStream());
            workbook.write(out);
        } catch (IOException e) {
            LOGGER.error("excel导出有误", e);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                LOGGER.error("读取内容有误", e);
            }
        }
    }

    /**
     * 下载资源
     */
    @GetMapping("downLoadVideo")
    private void downLoad(String fileUrl, HttpServletResponse response) throws IOException {

    }

    @GetMapping("/downloadExcelStu")
    public void downloadExcelStu(HttpServletResponse response, HttpServletRequest request) throws Exception {
        //文件名和路径前面已经传来了，所以不需要了
        //1.获取要下载的文件的绝对路径
        //String realPath = this.getServletContext().getRealPath("/download/1.JPG");
        String fileUrl = QINIU_FILE_DIRECTORY + "studentTemplate002.xls";
        //2.获取要下载的文件名
        URL url = new URL("http://jinruanresource.shixuncloud.com/" + fileUrl);
        //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("studentTemplate.xls", "UTF-8"));
        //通知客服文件的MIME类型
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        //4.获取要下载的文件输入流
        //2.获取链接
        URLConnection conn = url.openConnection();
        conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        conn.addRequestProperty("referer", "jinruancloud.com");
        //3.输入流
        InputStream inStream = conn.getInputStream();
        int len = 0;
        //5.创建数据缓冲区
        byte[] buffer = new byte[1024];
        //6.通过response对象获取OutputStream流
        OutputStream out = response.getOutputStream();
        //7.将FileInputStream流写入到buffer缓冲区
        while ((len = inStream.read(buffer)) > 0) {
            //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
            out.write(buffer, 0, len);
        }
        inStream.close();
    }

    /**
     * 教师管理
     */
    @GetMapping("/downloadExcelTea")
    public void downloadExcelTea(HttpServletResponse response, HttpServletRequest request) throws Exception {
        //文件名和路径前面已经传来了，所以不需要了
        //1.获取要下载的文件的绝对路径
        //String realPath = this.getServletContext().getRealPath("/download/1.JPG");
        String fileUrl = QINIU_FILE_DIRECTORY + "1600392523286.xls";
        //2.获取要下载的文件名
        URL url = new URL("http://jinruanresource.shixuncloud.com/" + fileUrl);
        //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("teaTemplate.xls", "UTF-8"));
        //通知客服文件的MIME类型
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        //4.获取要下载的文件输入流
        //2.获取链接
        URLConnection conn = url.openConnection();
        conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        conn.addRequestProperty("referer", "jinruancloud.com");
        //3.输入流
        InputStream inStream = conn.getInputStream();
        int len = 0;
        //5.创建数据缓冲区
        byte[] buffer = new byte[1024];
        //6.通过response对象获取OutputStream流
        OutputStream out = response.getOutputStream();
        //7.将FileInputStream流写入到buffer缓冲区
        while ((len = inStream.read(buffer)) > 0) {
            //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
            out.write(buffer, 0, len);
        }
        inStream.close();
    }

    @GetMapping("/downloadExcelUser")
    public void downloadExcelUser(HttpServletResponse response, HttpServletRequest request) {
        //方法一：直接下载路径下的文件模板
        try {
            //获取要下载的模板名称
            String fileName = "userMB.xls";
            //设置要下载的文件的名称
            response.setHeader("Content-disposition", "attachment;fileName=" + fileName);
            //通知客服文件的MIME类型
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            //获取文件的路径
            String filePath = getClass().getResource("/template/" + fileName).getPath();
            FileInputStream input = new FileInputStream(filePath);
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = input.read(b)) != -1) {
                out.write(b, 0, len);
            }
            //修正 Excel在“xxx.xlsx”中发现不可读取的内容。是否恢复此工作薄的内容？如果信任此工作簿的来源，请点击"是"
            response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
            input.close();
            //return Response.ok("应用导入模板下载完成");
            //return new ApiReturnObject("200","导入成功","");
        } catch (Exception ex) {
            LOGGER.error("getApplicationTemplate :", ex);
            //return Response.ok("应用导入模板下载失败！");
            //return new ApiReturnObject("201","导入失败","");
        }
    }


    @GetMapping("/downloadExcel2")
    public void downloadExcel2(HttpServletResponse response, HttpServletRequest request) {
        //方法二：可以采用POI导出excel，但是比较麻烦
        try {
            Workbook workbook = new HSSFWorkbook();
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download");


            String filedisplay = "外部案件导入模板.xls";

            filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);

            // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
            Sheet sheet = workbook.createSheet("外部案件导入模板");
            // 第三步，在sheet中添加表头第0行
            Row row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            CellStyle style = workbook.createCellStyle();
            //style.setAlignment(CellStyle.ALIGN_CENTER); // 创建一个居中格式

            Cell cell = row.createCell(0);
            cell.setCellValue("商品名称");
            cell.setCellStyle(style);
            sheet.setColumnWidth(0, (25 * 256));  //设置列宽，50个字符宽

            cell = row.createCell(1);
            cell.setCellValue("商品编码");
            cell.setCellStyle(style);
            sheet.setColumnWidth(1, (20 * 256));  //设置列宽，50个字符宽

            cell = row.createCell(2);
            cell.setCellValue("商品价格");
            cell.setCellStyle(style);
            sheet.setColumnWidth(2, (15 * 256));  //设置列宽，50个字符宽

            cell = row.createCell(3);
            cell.setCellValue("商品规格");
            cell.setCellStyle(style);
            sheet.setColumnWidth(3, (15 * 256));  //设置列宽，50个字符宽

            // 第五步，写入实体数据 实际应用中这些数据从数据库得到
            row = sheet.createRow(1);
            row.createCell(0, Cell.CELL_TYPE_STRING).setCellValue(1);
            row.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(2);
            row.createCell(2, Cell.CELL_TYPE_STRING).setCellValue(3);  //商品价格
            row.createCell(3, Cell.CELL_TYPE_STRING).setCellValue(4);  //规格

            // 第六步，将文件存到指定位置
            try {
                OutputStream out = response.getOutputStream();
                workbook.write(out);
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
